package com.spsoft.vatoutinv.jobHandler;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.spsoft.vatoutinv.service.vmsfulloutinvoice.VmsFullOutInvoiceDetailsService;
import com.spsoft.vms.redis.service.impl.InvoiceFileCreateVmsQueueServiceImpl;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 生成版式文件定时任务
 *
 * @author wangy
 * @date 2024/2/7 13:26
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class VmsBswjDownloadJob {

    public static final String LOG_MSG = "(生成版式文件定时任务)";

    private final InvoiceFileCreateVmsQueueServiceImpl invoiceFileCreateVmsQueue;

    private final VmsFullOutInvoiceDetailsService fullOutInvoiceDetailsService;

    @XxlJob("vmsBswjDownloadJobHandler")
    public ReturnT<String> vmsBswjDownloadJob() {
        long start = System.currentTimeMillis();
        XxlJobHelper.log("{}开始执行", LOG_MSG);

        // 获取生成版式文件队列中的发票号码
        int queueSize = invoiceFileCreateVmsQueue.getQueueSize();
        List<String> fphmList = invoiceFileCreateVmsQueue.getMessagesFromQueue(queueSize);

        if (CollectionUtil.isNotEmpty(fphmList)) {
            HashMap<String, String> map = new HashMap<>();
            XxlJobHelper.log("{}等待生成版式文件的发票数量：{}，发票号码：{}",
                    LOG_MSG, fphmList.size(), JSONObject.toJSONString(fphmList));
            CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
                try {
                    map.putAll(fullOutInvoiceDetailsService.fileDownload(fphmList, "pdf"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
                try {
                    map.putAll(fullOutInvoiceDetailsService.fileDownload(fphmList, "xml"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            // 等待所有任务完成，注意get方法，是阻塞式等待，等待上面的异步任务都完成
            try {
                CompletableFuture.allOf(future1, future2).get();
            } catch (Exception e) {
                XxlJobHelper.log("{}出现异常：{}", LOG_MSG, e);
            }

            // 遍历 pdf map 和 xml map
            if (ObjectUtils.isNotEmpty(map) && !map.isEmpty()) {
                map.forEach((k, v) -> {
                    if (v != null) {
                        XxlJobHelper.log("{}发票号码：{}下载失败，失败原因：{}机构未开启版式文件下载开关", LOG_MSG, k, v);
                    }
                });
            }
        } else {
            XxlJobHelper.log("{}等待生成版式文件的发票数量：0", LOG_MSG);
        }

        long end = System.currentTimeMillis();
        XxlJobHelper.log("{}执行完成，用时：{}ms", LOG_MSG, end - start);
        return ReturnT.SUCCESS;
    }
}